<template>
  <ElDrawer size="80%" :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="设备名称" prop="deviceName">
        <el-input v-model="formData.deviceName" placeholder="请输入设备名称" />
      </el-form-item>
      <el-form-item label="型号" prop="model">
        <el-input v-model="formData.model" placeholder="请输入型号" />
      </el-form-item>
      <el-form-item label="设备分类" prop="categoryId">
        <el-tree-select
          v-model="formData.categoryId"
          :data="deviceCategoryTree"
          :props="{ ...defaultProps, label: 'categoryName' }"
          check-strictly
          default-expand-all
          placeholder="请选择设备分类"
        />
      </el-form-item>
      <el-form-item label="单价" prop="price">
        <el-input v-model="formData.price" placeholder="请输入单价" />
      </el-form-item>
      <el-form-item label="计量单位" prop="unit">
        <el-select v-model="formData.unit" placeholder="请选择计量单位">
          <el-option label="件" value="件" />
          <el-option label="台" value="台" />
          <el-option label="套" value="套" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备参数" prop="attributes">
        <el-input type="textarea" :rows="10" v-model="formData.attributes" placeholder="请输入设备参数" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :value="1">在售</el-radio>
          <el-radio :value="0">下架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注信息" prop="remark">
        <el-input type="textarea" :rows="3" v-model="formData.remark" placeholder="请输入备注信息" />
      </el-form-item>
      <el-form-item label="图片" prop="deviceImage">
        <UploadImg v-model="formData.deviceImage" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </ElDrawer>
</template>
<script setup lang="ts">
import { DeviceApi, DeviceVO } from '@/api/agent/device/device'
import { DeviceCategoryApi } from '@/api/agent/device/devicecategory'
import { defaultProps, handleTree } from '@/utils/tree'

/** 设备信息主 表单 */
defineOptions({ name: 'DeviceForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  deviceName: undefined,
  model: undefined,
  categoryId: undefined,
  price: undefined,
  unit: undefined,
  attributes: undefined,
  status: undefined,
  remark: undefined,
  deviceImage: undefined
})
const formRules = reactive({
  deviceName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择设备分类', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref
const deviceCategoryTree = ref([])

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DeviceApi.getDevice(id)
    } finally {
      formLoading.value = false
    }
  }
  await getDeviceCategoryTree()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as DeviceVO
    if (formType.value === 'create') {
      await DeviceApi.createDevice(data)
      message.success(t('common.createSuccess'))
    } else {
      await DeviceApi.updateDevice(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    deviceName: undefined,
    model: undefined,
    categoryId: undefined,
    price: undefined,
    unit: undefined,
    attributes: undefined,
    status: undefined,
    remark: undefined,
    deviceImage: undefined
  }
  formRef.value?.resetFields()
}

/** 获得设备分类树 */
const getDeviceCategoryTree = async () => {
  deviceCategoryTree.value = []
  const data = await DeviceCategoryApi.getDeviceCategoryList()
  const root = { id: 0, categoryName: '顶级设备分类', children: [] as any[] }
  root.children = handleTree(data, 'id', 'parentId')
  deviceCategoryTree.value.push(root)
}
</script>